package com.dhh.sky.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.dhh.sky.R;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.service.CopyOperationService;
import com.dhh.sky.service.MoveOperationService;
import com.dhh.sky.util.Constant;
import com.dhh.sky.util.FileManager;
import com.dhh.sky.widget.FileChooseListAdapter;

public class FolderChooseActivity extends BasicActivity{
	private ListView listView;
	private FileChooseListAdapter adapter;
	private FileManager fm;
	private MenuItem paste;
	private String currentPath = Constant.SKYFRIVE_PATH_HOME;
	private LinearLayout loading;
	private int requestCode = 0;
	private String oPath;
	private String[] ids;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.file_list); 
		
		fm = new FileManager(this);
		requestCode = this.getIntent().getExtras().getInt(Constant.PARAM_REQUEST);
		oPath = this.getIntent().getExtras().getString(Constant.PARAM_PATH);
		ids = this.getIntent().getExtras().getStringArray(Constant.PARAM_ITEM_NAME);
		initView();
	}
	
	public void initView(){
		initActionBar();
		loading = (LinearLayout) this.findViewById(R.id.td_loading);
		listView = (ListView) this.findViewById(R.id.file_list);
		adapter = new FileChooseListAdapter(this,currentPath);
		listView.setTextFilterEnabled(true);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				currentPath = adapter.getItem(position).getId();
				adapter.setPath(currentPath);
				initData();
			}
		});
	}
	
	@Override
	public void onResume(){
		super.onResume();
		initData();
	}
	
	@Override
	public void initActionBar(){
		if(Constant.REQ_OPERATION_COPY == requestCode){
			getSupportActionBar().setTitle(this.getString(R.string.title_copy_to));
		}else if(Constant.REQ_OPERATION_MOVE == requestCode){
			getSupportActionBar().setTitle(this.getString(R.string.title_move_to));			
		}
		getSupportActionBar().setDisplayShowHomeEnabled(false);    
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);   
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(Constant.SKYFRIVE_PATH_HOME.equalsIgnoreCase(currentPath)){
				//TODO show dialog to indicate current is top folder.
			}else{
				SkyDriveObject file = fm.getFile(currentPath);
				if(file!=null){
					currentPath = file.getParentId();
				}else{
					currentPath = Constant.SKYFRIVE_PATH_HOME;
				}		
				this.initData();
				
				return true;
			}
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem cancelItem = menu.add(getString(R.string.label_cancel));
		cancelItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		cancelItem.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				setResult(-1, null);
				finish();
				return true;
			}});
		
		paste = menu.add(getString(R.string.label_ok));
		paste.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		paste.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				if(Constant.REQ_OPERATION_COPY == requestCode){
					om.addCopyOperation(ids, currentPath);
					Intent intent = new Intent(FolderChooseActivity.this,CopyOperationService.class);
					FolderChooseActivity.this.startService(intent);
				}else if(Constant.REQ_OPERATION_MOVE == requestCode){
					om.addMoveOperation(ids, currentPath);
					Intent intent = new Intent(FolderChooseActivity.this,MoveOperationService.class);
					FolderChooseActivity.this.startService(intent);
				}
				
				Intent data = new Intent();
				setResult(requestCode, data);
				finish();
				
				return true;
			}});
		return true;
	}
	
	public void initData(){
		if(paste!=null)
			paste.setEnabled(!currentPath.equals(oPath));
		adapter.setPath(currentPath);
		adapter.loadFiles();
		adapter.notifyDataSetChanged();	
		
		if(fm.needSync(currentPath)){
			if(adapter.getCount()>0){
				setSupportProgressBarIndeterminateVisibility(true);
			}else if(fm.getFolderChildrenCount(currentPath)>0){
				listView.setVisibility(View.GONE);
				loading.setVisibility(View.VISIBLE);
			}
			
			new FileSyncTask().execute();
		}
	}
	
	public class FileSyncTask extends AsyncTask<Void, Void, Boolean>{
		@Override
		protected Boolean doInBackground(Void... params) {
			fm.doSync(FolderChooseActivity.this, currentPath);
			return true;
		}
		
		@Override
        protected void onPostExecute(final Boolean isLogin) {
			refreshHandler.sendEmptyMessage(0);
		}
		
	}
	
	private Handler refreshHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {    
    		listView.setVisibility(View.VISIBLE);
    		loading.setVisibility(View.GONE);
    		setSupportProgressBarIndeterminateVisibility(false);
    		
    		adapter.setPath(currentPath);
    		adapter.loadFiles();
    		adapter.notifyDataSetChanged();
        }
    };

	@Override
	void refresh() {
		
	}

	@Override
	protected void updateItemProgress(boolean isSucc, String path, String id,
			int progress) {
		
	}

}
